package com.user.query.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * s守护线程工程类
 * Created by bgt on 2017/3/15.
 */
public class DeamonsThreadFactory implements ThreadFactory{
    @Override
    public Thread newThread(Runnable r) {
        Thread t=new Thread(r);
        t.setDaemon(true);
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        //测试守护线程
        /*ExecutorService executorService= Executors.newCachedThreadPool(new DeamonsThreadFactory());
        for (int i=0;i<5;i++) {
            executorService.execute(new fromDeamonsThreadFactory());
        }
        System.out.println("run begin");
        TimeUnit.MILLISECONDS.sleep(570);
        executorService.shutdown();*/
        //测试守护线程创建的线程
        Thread thread=new Thread(new Daemons());
        thread.setDaemon(true);
        thread.start();
        TimeUnit.SECONDS.sleep(1);
    }
}

/**
 * 测试守护线程创建的线程是否也是守护线程
 *
 * res:true
 *
 * 如果是后台线程的话，final里面是不会执行的  后台线程有自己的一套执行逻辑
 */
class Daemons implements Runnable {
    private  Thread[] threads=new Thread[10];
    @Override
    public void run() {
        try {
            for (int i=0;i<10;i++) {
                threads[i]=new Thread();
                threads[i].start();
                System.out.println(threads[i].isDaemon());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}
/**
 * 线程工厂使用类
 */
class fromDeamonsThreadFactory implements Runnable {

    @Override
    public void run() {
        try {
            while (true) {
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println("执行了"+Thread.currentThread()+this.toString());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
